const xlsx = require('xlsx');
const node_xlsx = require('node-xlsx');
const fs = require('fs');
const _ = require('lodash');
const csv = require('fast-csv');
const moment = require('moment');
// const csvFile = require('./CsvFile');

let csvHeaders = ['任务批次','用户账号','号码','信息内容','通道','提交时间','提交状态','返回信息','状态报告','回执时间','状态报告值'];

let targetPath = '/Volumes/DATA_HD/mobiles/smsDetailList.csv';

const csvStream = csv.format({
    headers : csvHeaders,
    writeHeaders: false
});

const myUtil = require('./utils');
var iconv = require('iconv-lite');

let filePath = './list.xlsx';


let rs = fs.createReadStream(filePath);
let ws = fs.createWriteStream(targetPath, {flags : 'a'});
//
ws.write(`
`, err => {});

process_RS(rs, myUtil.commonHandler);

function process_RS(stream/*:ReadStream*/, cb/*:(wb:Workbook)=>void*/)/*:void*/{
    var buffers = [];
    stream.on('data', function(data) { buffers.push(data); });
    stream.on('end', function() {
        var buffer = Buffer.concat(buffers);

        // buffer = iconv.decode(buffer,'gbk');
        var wb = xlsx.read(buffer, {type:"buffer"});

        /* DO SOMETHING WITH workbook IN THE CALLBACK */
        let first_sheet_name = wb.SheetNames[0];

        /* Get worksheet */
        let ws = wb.Sheets[first_sheet_name];
        let xlsList = cb(ws);

        gen(xlsList.data, 30000000);
    });
}

function gen(seed, amount){
    console.log('hello, let`s do it');

    csvStream.pipe(ws).on('end', () => {console.log('done');});
    let a = seed.length;

    let loopTime = (amount / a);
    let count = 0;
    for(let i = 0; i < loopTime; i++){


        for(let item of seed){
            let r = Math.round((Math.random() * 100));
            item['任务批次'] = +item['任务批次'] + r;
            item['号码'] = getMobile();
            if(item['回执时间']){
                item['回执时间'] = moment(item['回执时间']).add(r, 'second').format('YYYY-MM-DD HH:mm:ss');
            }else{
                item['回执时间'] = '';
            }
            if(!item['状态报告']){
                item['状态报告'] = '';
            }
            csvStream.write(item);
            count++;
            // console.log(count);
        }
        // csvStream._flush(error => {if(error)console.log(error)});
        console.log(moment().format('YYYY-MM-DD HH:mm:ss'), i, loopTime);

    }
    ws.write(`
`, err => {});

    csvStream.end();




}

const cmPre = ['134','135','136','137','138','139','147','148','150','151','152','157','158','159','178','182','183','184','187','188','198'];

function getMobile(){
    let r = Math.random();
    let pre = cmPre[Math.floor(r * cmPre.length)];
    let body = myUtil.randomStr(8);
    return pre + body;
}

// g();